package cn.tpshion.config.support;

import cn.tpshion.config.common.BusinessException;
import cn.tpshion.config.common.ErrorCode;
import cn.tpshion.config.common.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证拦截器
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    private static final String TOKEN = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行options请求类型
        if(HttpMethod.OPTIONS.toString().equals(request.getMethod().toString())){
            return true;
        }

        //如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //验证token，该token可以放置在请求头和请求参数中
        String token = StringUtils.hasText(request.getHeader(TOKEN)) ? request.getHeader(TOKEN) : request.getParameter(TOKEN);
        if(!StringUtils.hasText(token)){
            log.info("[{}] {} 请求未授权", request.getMethod(), request.getServletPath());
            throw new BusinessException(ErrorCode.NO_ACCESS);
        }
        JwtUtil.checkToken(token);
        return true;
    }
}
